package com.nifostasky.config;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 数学运算验证码:
 *  验证码文本生成器 , 即 文本生成规则
 */
public class KaptchaTextCreator extends DefaultTextCreator {

    private static final String[] CNUMBERS = {"0","1","2","3","4","5","6","7","8","9","10"};

    /**
     * 文本生成规则
     * @return
     */
    @Override
    public String getText() {
        Integer result = 0;
        Random random = new SecureRandom();
        int x = random.nextInt(10);
        int y = random.nextInt(10);
        StringBuilder suChinese = new StringBuilder();
        //Math.round,取浮点数距离最近的一个整数, 例如 3.1 与 3 , 4 相比 距离 3 更近,所以取3; 如果为3.5,则取大,取4;
        Long randomOperands = Math.round(Math.random() * 2);

        switch (randomOperands.intValue()){
            //乘
            case 0:
                result = x * y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("*");
                suChinese.append(CNUMBERS[y]);
                break;
            //除
            case 1:
                if (!(x == 0) && y % x == 0)
                {
                    result = y / x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("/");
                    suChinese.append(CNUMBERS[x]);
                }
                else
                {
                    result = x + y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("+");
                    suChinese.append(CNUMBERS[y]);
                }
                break;
            //减
            case 2:
                if (x >= y)
                {
                    result = x - y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[y]);
                }
                else
                {
                    result = y - x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[x]);
                }
                break;
            //加
            default:
                result = x + y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("+");
                suChinese.append(CNUMBERS[y]);
                break;
        }
        suChinese.append("=?@" + result);

        return suChinese.toString();
    }
}
